package com.jun.controller.user;

import com.jun.pojo.entity.SysUser;
import com.jun.pojo.vo.R;
import com.jun.pojo.vo.SysUserVo;
import com.jun.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sysUser")
public class SysUserController {
    private static String newPassword;
    @Autowired
    private SysUserService sysUserService;

    /**
     * 用户登录
     * @param sysUser 接受实体类
     */
    @PostMapping("/login")
    public R selectSysUser(@Validated @RequestBody SysUser sysUser) {
        SysUser user = sysUserService.getUser(sysUser);
        if (user == null) {
            return new R().error();
        }
        return new R(user);
    }

    /**
     * 注册用户
     * @param sysUserVo 接受实体类
     */
    @PostMapping("/save")
    public R insertSysUser(@Validated @RequestBody SysUserVo sysUserVo){
        Map<String, String> result = new HashMap<>();

        String newPassword = sysUserVo.getNewPassword();
        String newPasswordAgain = sysUserVo.getNewPasswordAgain();
        if (
            StringUtils.hasText(newPassword) &&
            StringUtils.hasText(newPasswordAgain)
        ) {
            // 判断密码与二次密码是否一致
            if (newPassword.equals(newPasswordAgain)) {
                boolean save = sysUserService.saveUser(sysUserVo);
                if (save) {
                    return new R().success();
                }
            } else {
                result.put("newPasswordAgain", "与密码不一致");
            }
        }
        return new R(result);
    }

    /**
     * 修改用户密码
     * @param sysUserVo 接受实体类
     */
    @PutMapping
    public R updateSysUser(@Validated @RequestBody SysUserVo sysUserVo){
        Map<String, String> result = new HashMap<>();

        String newPassword = sysUserVo.getNewPassword();
        String newPasswordAgain = sysUserVo.getNewPasswordAgain();
        if (
            StringUtils.hasText(newPassword) &&
            StringUtils.hasText(newPasswordAgain)
        ) {
            // 判断密码与二次密码是否一致
            if (newPassword.equals(newPasswordAgain)) {
                int i = sysUserService.updateUser(sysUserVo);
                if (i == 1) {
                    return new R().success();
                }
            } else {
                result.put("newPasswordAgain", "与密码不一致");
            }
        }
        return new R(result);
    }
}
